package org.jackysoft.service.impl;

import java.util.Collection;
import java.util.Set;

import javax.annotation.Resource;

import org.jackysoft.data.AbstractDataProvider;
import org.jackysoft.entity.SecurityRole;
import org.jackysoft.entity.TreeNode;
import org.jackysoft.mapper.SecurityRoleMapper;
import org.jackysoft.service.SecurityRoleService;
import org.jackysoft.spring.event.SecurityRoleChanageEvent;
import org.jackysoft.util.ClassUtils;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.google.common.collect.Sets;

@Service
public class SecurityRoleServiceImpl extends
		AbstractDataProvider<SecurityRole> implements
		SecurityRoleService ,ApplicationEventPublisherAware{

	
	@Resource
	SecurityRoleMapper mapper;
	
	private ApplicationEventPublisher publisher;
	public SecurityRoleServiceImpl() {
		super();
	}

	
	@Override
	public void save(SecurityRole t) {
		String name = "ROLE_".concat(ClassUtils.generateRString());
		t.setName(name);
		t.setEnabled(true);
		mapper.inert(t);
		fireEvent();
	}	
	
	
	@Override
	public void update(SecurityRole a) throws DataAccessException {

		Collection<TreeNode> trees = a.getTreeNode();

		Set<TreeNode> nodes = Sets.newHashSet();

		nodes.addAll(trees);

		a.setTreeNode(nodes);

		a.setEnabled(true);

		super.update(a);

		fireEvent();
	}

	@Override
	public Collection<SecurityRole> getsByUrl(String treeid)
			throws DataAccessException {
		Collection<SecurityRole> list = mapper.findByTreeNode(treeid);
		return list;
	}

	
	@Override
	public Collection<SecurityRole> findByUser(String user) throws DataAccessException {
		Collection<SecurityRole> list = mapper.findByUser(user);
		return  list;
	}
	

	@Override
	public int[] appendUsers(String role, Collection<String> users)
			throws DataAccessException {
		for(String user:users){
			mapper.appendUser(role, user);
		}
		return null;
	}

	@Override
	public boolean hasRole(String user,String role){
		int i = mapper.hasRole(user, role);
	    return i>0;
	}
	

	@Override
	public void enabled(String role) {
		mapper.enabled(role);
		fireEvent();
	}

	private void fireEvent() {
		this.publisher.publishEvent(new SecurityRoleChanageEvent(this));
	}

	@Override
	public void notifyDone(String id) {
		notifyService.doneEvent(id);

	}


	@Override
	public void setApplicationEventPublisher(
			ApplicationEventPublisher applicationEventPublisher) {
		 this.publisher = applicationEventPublisher;
		
	}


	@Override
	public Collection<SecurityRole> findEnabledByUser(String user)
			throws DataAccessException {
		Collection<SecurityRole> list = mapper.findEnabledByUser(user);
		return list;
	}	
}
